﻿using System.Web.Mvc;
using CNav.Business.Services;
using CNav.Domain.Admin;
using CNav.Support;
using WebGrease.Css.Extensions;

namespace CNav.Controllers
{
    [Authorize]
    [AdminAuthorize]
    public class DataSourceController : BaseController
    {
        public ActionResult Index()
        {
            var dataSourceList = Service.Get<IUiService>().GetDataSourceList();
            return View(dataSourceList.Data);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(DataSource datasource)
        {
            if (ModelState.IsValid)
            {
                Service.Get<IUiService>().AddDataSource(datasource);
                return RedirectToAction("Index");
            }

            return View(datasource);
        }

        public ActionResult Edit(int id = 0)
        {
            var response = Service.Get<IUiService>().GetDataSourceById(id);
            if (response.Data == null)
            {
                return View("NotFound");
            }
            return View(response.Data);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(DataSource datasource)
        {
            if (ModelState.IsValid)
            {
                var response = Service.Get<IUiService>().UpdateDataSource(datasource);
                if (response.Error == null)
                    return RedirectToAction("Index");

                response.Error.ForEach(e => ModelState.AddModelError("", e));
            }

            return View(datasource);
        }


        public ActionResult Delete(int id = 0)
        {
            var response = Service.Get<IUiService>().GetDataSourceById(id);

            if (response.Data == null)
            {
                return View("NotFound");
            }
            return View(response.Data);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Service.Get<IUiService>().DeleteDataSource(id);
            return RedirectToAction("Index");
        }
    }
}